package com.hk.service.order.impl;
import com.hk.commons.StringHelper;
import com.hk.commons.entity.Agreement;
import com.hk.commons.entity.order.OrderInfo;
import com.hk.commons.entity.product.ProductInfo;
import com.hk.service.kyc.IAgreement;
import com.hk.service.kyc.ICoupon;
import com.hk.service.order.IContract;
import com.hk.service.order.IOrderContract;
import com.hk.service.order.IOrderInfo;
import com.hk.service.product.IProductInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

@Service
public class ContractImpl  implements IContract {
	private Logger logger = LoggerFactory.getLogger(ContractImpl.class);

	@Value("${pdf.address}")
	private String FILE_DIR;

	@Value("${pdf.FTP_URL}")
	private String FTP_URL;

	@Value("${pic.address}")
	private String PIC_ADDRESS;


	@Value("${pic.tzqrh_back_img}")
	private String TZQRH_BACK_IMG;

	@Value("${pic.tzqrh_yz_img}")
	private String TZQRH_YZ_IMG;

	@Value("${qingniu.pdf}")
	private String QM_PDF;
	@Autowired
	private IOrderInfo orderService;

	@Autowired
	private IProductInfo productService;


	@Autowired
	private IAgreement agreementService;


	@Autowired
	private IOrderContract orderContractService;

	@Autowired
	ICoupon couponService;

	@Override
	public Boolean create(long orderId) {
		Boolean resultPDF = false;
		Boolean resultHTML = false;
		OrderInfo orderInfo = orderService.findById(orderId);
		Long productId = orderInfo.getProductId();

		ProductInfo productInfo = productService.findById(productId);
		if(productInfo == null){
			return false;
		}

		Long agreementId = productInfo.getContractId();

		Agreement agreement = agreementService.findById(agreementId);

		String contractPDFUrl = orderContractService.getPDFContarctUrlByOrder(orderId, agreementId);

		if(StringHelper.isNotEmpty(contractPDFUrl)){
			orderService.setContractUrl(orderId, contractPDFUrl, agreement.getName());
			resultPDF = true;
		}

		String contractHTMLUrl = orderContractService.getHTMLContarctUrlByOrder(orderId, agreementId);
		if(StringHelper.isNotEmpty(contractHTMLUrl)){
			orderService.setContractUrlHtml(orderId, contractHTMLUrl);
			resultHTML = true;
		}


		return  resultPDF && resultHTML;
	}

    @Override
    public Boolean creatTZQRHPDF(Long orderId) {
        Boolean result = false;

        String contractTZQRHUrl = orderContractService.getTZQRHPDFUrl(orderId);

        if (StringHelper.isNotEmpty(contractTZQRHUrl)) {
            result = true;
        }
        return result;
    }


	//	@Override
//	public Boolean create(long orderId) {
//		OrderInfo orderInfo = orderService.findById(orderId);
//
//		if(orderInfo == null){
//			return false;
//		}
//
//		Long productId = orderInfo.getProductId();
//
//		ProductInfo productInfo = productService.findById(productId);
//		if(productInfo == null){
//			return false;
//		}
//
//		Long agreementId = productInfo.getContractId();
//
//		Agreement agreement = agreementService.findById(agreementId);
//
//		String contractMsg = agreementService.getByInfo(agreementId, orderInfo.getUserId(), orderInfo.getSuccessAmount().toString());
//
//		contractMsg = contractMsg.replace("88888888", String.valueOf(orderId));
//
//		try {
//			//页面大小
//			Rectangle rect = new Rectangle(PageSize.A4);
//
//			//页面背景色
//			rect.setBackgroundColor(BaseColor.WHITE);
//
//			Document document = new Document(rect);
//
//
//			String filePath =  getCode() + ".pdf";
//
//			logger.info("filePath = {}", filePath);
//			//Step 2—Get a PdfWriter instance.
//			PdfWriter writer =  PdfWriter.getInstance(document, new FileOutputStream(filePath));
//
//			//Step 3—Open the Document.
//			document.open();
//
//			InputStream inputStream = new ByteArrayInputStream(this.getContent(contractMsg).getBytes("UTF-8"));
//
//
//			// 使用我们的字体提供器，并将其设置为unicode字体样式
//			MyFontsProvider fontProvider = new MyFontsProvider();
//			fontProvider.addFontSubstitute("lowagie", "garamond");
//			fontProvider.setUseUnicode(true);
//			CssAppliers cssAppliers = new CssAppliersImpl(fontProvider);
//			HtmlPipelineContext htmlContext = new HtmlPipelineContext(cssAppliers);
//			htmlContext.setTagFactory(Tags.getHtmlTagProcessorFactory());
//
//			XMLWorkerHelper.getInstance().getDefaultCssResolver(true);
//
//			XMLWorkerHelper.getInstance().parseXHtml(writer, document, inputStream, null, Charset.forName("UTF-8"),
//					fontProvider);
//
//			logger.info("pdf will create ");
//			//XMLWorkerHelper. getInstance().parseXHtml(writer, document,  inputStream, Charset.forName("UTF-8"));
//
//			logger.info("pdf create finished");
//
//			// step 5
//			document.close();
//			writer.close();
//
//			logger.info("pdf will close");
//
//			String respStr = ftpSave(filePath, filePath);
//
//			logger.info("respStr = " + respStr);
//			org.codehaus.jackson.JsonNode result = JsonUtils.toJsonObject(respStr);
//
//			Boolean ftpResult = false;
//
//			if(result.get("success").getBooleanValue()){
//				ftpResult = true;
//				String contractUrl = result.get("file_path").toString();
//
//				logger.info("contractUrl =  "+ contractUrl );
//				if(StringHelper.isNotEmpty(contractUrl)){
//					orderService.setContractUrl(orderId, filePath, agreement.getName());
//				}
//
//
//				File file = new File(filePath);
//				if (file.isFile() && file.exists()) {
//					file.delete();
//					logger.info("contract will delete contract FILE  = {}", filePath);
//				}
//
//			}
//
//			//create Html File
//			creatHTMLFile( orderId,  contractMsg);
//
//		}catch ( Exception e){
//			logger.info("create pdf exception e={}", e);
//			return false;
//		}
//
//		return true;
//
//	}
//
//	private String getContent( String content) {
//		String result = "";
//		try{
//			StringBuilder sb = new StringBuilder();
//			sb.append("<html>");
//			sb.append("<head>");
//			//sb.append("<title>每日运营报表</title>");
//			sb.append("<meta name=\"viewport\" content=\"width=device-width, initial-scale=1, minimum-scale=1, maximum-scale=2.0, user-scalable=yes \" />");
//
//			sb.append("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />");
//
//			sb.append("</head><body><div style=\"width: 100%; word-break:break-all;\">");
//
//			content = content.replace("/upload/ueditor/jsp/upload/image/", PIC_ADDRESS);
//
//			sb.append(content);
//			sb.append("</div></body></html>");
//			result = sb.toString();
//
//		}catch ( Exception e){
//			logger.info("create excel exception e={}", e);
//		}
//
//		return result;
//	}
//
//	private String ftpSave(String filePath, String orderIdStr){
//		RestTemplate rest = new RestTemplate();
//		FileSystemResource resource = new FileSystemResource(new File(filePath));
//		MultiValueMap<String, Object> param = new LinkedMultiValueMap<>();
//		param.add("upload_file", resource);
//		param.add("contract_id", orderIdStr);
//
//		String string = rest.postForObject(FTP_URL, param, String.class);
//		return string;
//	}
//
//	/**
//	 * 重写 字符设置方法，解决中文乱码问题
//	 *
//	 */
//	public class MyFontsProvider extends XMLWorkerFontProvider {
//
//		public MyFontsProvider(){
//			super(null, null);
//		}
//
//		@Override
//		public Font getFont(final String fontname, String encoding, float size, final int style) {
//
//			//logger.info("old fontname ={}", fontname);
//			/**
//			 * String fntname = fontname;
//			 if (fntname == null) {
//			 fntname = "/usr/share/fonts/zh_CN/TrueType/simsun.ttf";
//			 }
//			 **/
//
//			String fntname = "WenQuanYi Zen Hei";
//
//			//logger.info("new  fontName = {}", fntname);
//
//			if (size == 0) {
//				size = 4;
//			}
//			return super.getFont(fntname, encoding, size, style);
//		}
//	}
//
//
//	//创建HTML文件
//	public void creatHTMLFile(Long orderId, String content) {
//
//		logger.info("creatHTMLFile contract orderId ={}", orderId);
//
//		String pathName = getCode() + ".html";
//
//		logger.info("pathName = {}", pathName);
//
//		String contractContent = getContent(content);
//		logger.info("creatHTMLFile pathName ={}", pathName);
//		try {
//			Path filePath = Paths.get(pathName);
//			Files.write(filePath, contractContent.getBytes("UTF-8"));
//		} catch (IOException e) {
//			logger.error("创建订单HTML 失败 orderId={}, e={}", orderId,  e);
//		}
//
//		String respStr = ftpSave(pathName, pathName);
//
//		logger.info("创建订单HTML respStr = " + respStr);
//		org.codehaus.jackson.JsonNode result = JsonUtils.toJsonObject(respStr);
//
//		Boolean ftpResult = false;
//
//		if(result.get("success").getBooleanValue()){
//			ftpResult = true;
//			String contractUrl = result.get("file_path").toString();
//
//			logger.info("创建订单HTML contractUrl =  "+ contractUrl );
//			if(StringHelper.isNotEmpty(contractUrl)){
//				orderService.setContractUrlHtml(orderId, pathName );
//			}
//
//			File file = new File(pathName);
//			if (file.isFile() && file.exists()) {
//				file.delete();
//				logger.info("contract will delete contract HTML FILE  = {}", pathName);
//			}
//
//		}
//
//	}
//
//
//	@Override
//	public Boolean creatTZQRHPDF(Long orderId) {
//        OrderInfo orderInfo = orderService.findById(orderId);
//
//        if (orderInfo == null) {
//            return false;
//        }
//
//        Long productId = orderInfo.getProductId();
//
//        ProductInfo productInfo = productService.findById(productId);
//        if (productInfo == null) {
//            return false;
//        }
//
//        //获取投资确认函ID
//        Long agreementId = agreementService.getTQRHId();
//
//        String contractMsg = agreementService.getByInfo(agreementId, orderInfo.getUserId(), orderInfo.getSuccessAmount().toString());
//
//        contractMsg = contractMsg.replace("88888888", String.valueOf(orderId));
//
//
//        Long tradeDate = orderInfo.getOrderTradeDate();
//
//        String tradeDateStr01 = DateUtil.longToShortDate(tradeDate);
//
//        String tradeDateStr02 = DateUtil.longToShortDateZW(tradeDate);
//
//        logger.info("contractMag = {}", contractMsg);
//
//        //替换起息日
//        contractMsg = contractMsg.replace("tradeDate01", tradeDateStr01);
//        contractMsg = contractMsg.replace("tradeDate02", tradeDateStr02);
//
//        //替换投资金额
//        BigDecimal buyAmount = orderInfo.getSuccessAmount();
//
//        contractMsg = contractMsg.replace("amount01", MoneyUtil.number2CNMontrayUnit(buyAmount));
//        contractMsg = contractMsg.replace("amount02", buyAmount.toString());
//
//        //替换投资期限
//        contractMsg = contractMsg.replace("term", orderInfo.getTerm().toString());
//
//        //替换产品名称
//        contractMsg = contractMsg.replace("prodName", productInfo.getName());
//
//        if (StringHelper.isNotEmpty(orderInfo.getContractTitle())) {
//            //替换合同名称
//            contractMsg = contractMsg.replace("contractTitle", orderInfo.getContractTitle());
//        } else {
//            String content = "电子合同";
//            //如果订单没有生成电子合同
//            Agreement agr = agreementService.findById(productInfo.getContractId());
//            if (agr != null) {
//                content = agr.getName();
//            }
//
//            contractMsg = contractMsg.replace("contractTitle", content);
//
//        }
//
//        //替换空格占位符,一个#代表半个空格占位符
//        contractMsg = contractMsg.replace("#", " ");
//
//
//        try {
//            //页面大小
//            Rectangle rect = new Rectangle(PageSize.A4);
//
//
//            //页面背景色
//            rect.setBackgroundColor(BaseColor.WHITE);
//
//            Document document = new Document(rect);
//
//            String filePath = orderId + "_confirm_" + getCode() + ".pdf";
//
//            String filePath_yz = getCode() + ".pdf";
//
//            //Step 2—Get a PdfWriter instance.
//            PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(filePath));
//
//            //Step 3—Open the Document.
//            document.open();
//
//            Image tImgCover = Image.getInstance(TZQRH_BACK_IMG);
//
//            /* 设置图片的位置 */
//            tImgCover.setAbsolutePosition(0, 0);
//
//            /* 设置图片的大小 */
//            tImgCover.scaleAbsolute(PageSize.A4); // .scaleAbsolute(595, 842);
//            document.add(tImgCover);
//
//            InputStream inputStream = new ByteArrayInputStream(this.getContent(contractMsg).getBytes("UTF-8"));
//
//            // 使用我们的字体提供器，并将其设置为unicode字体样式
//            MyFontsProvider fontProvider = new MyFontsProvider();
//            fontProvider.addFontSubstitute("lowagie", "garamond");
//            fontProvider.setUseUnicode(true);
//            CssAppliers cssAppliers = new CssAppliersImpl(fontProvider);
//            HtmlPipelineContext htmlContext = new HtmlPipelineContext(cssAppliers);
//            htmlContext.setTagFactory(Tags.getHtmlTagProcessorFactory());
//
//            XMLWorkerHelper.getInstance().getDefaultCssResolver(true);
//
//            XMLWorkerHelper.getInstance().parseXHtml(writer, document, inputStream, null, Charset.forName("UTF-8"),
//                    fontProvider);
//
//            logger.info("投资确认函 pdf will create ");
//            //XMLWorkerHelper. getInstance().parseXHtml(writer, document,  inputStream, Charset.forName("UTF-8"));
//
//            logger.info("投资确认函 pdf create finished");
//
//            // step 5
//            document.close();
//            writer.close();
//
//            logger.info("投资确认函 pdf will close");
//
//            sign(filePath, filePath_yz);
//
//            String respStr = ftpSave(filePath_yz, filePath_yz);
//
//            logger.info("respStr = " + respStr);
//            org.codehaus.jackson.JsonNode result = JsonUtils.toJsonObject(respStr);
//
//
//            if (result.get("success").getBooleanValue()) {
//                String confirmPDFUrl = result.get("file_path").toString();
//
//                logger.info("投资确认函 pdfUrl =  {}, orderId={}", confirmPDFUrl, orderId);
//                if (StringHelper.isNotEmpty(confirmPDFUrl)) {
//
//                    // create pdf take long time, get latest record for update
//                    orderInfo = orderService.findById(orderId);
//                    orderInfo.setConfirmationTitle("投资确认函");
//                    orderInfo.setConfirmationPdf(filePath_yz);
//                    orderService.update(orderInfo);
//                }
//
//                File file = new File(filePath);
//                if (file.isFile() && file.exists()) {
//                    file.delete();
//                    logger.info("contract will delete contract FILE  = {}", filePath);
//                }
//
//                File file_yz = new File(filePath_yz);
//                if (file_yz.isFile() && file_yz.exists()) {
//                    file_yz.delete();
//                    logger.info("contract will delete contract FILE  = {}", filePath);
//                }
//            }
//
//        } catch (Exception e) {
//            logger.info("create pdf exception e={}", e);
//            return false;
//        }
//        return true;
//    }
//
//	public void sign(String source01, String source02 )  {
//		try{
//			PdfReader reader = new PdfReader(source01);//选择需要印章的pdf
//			PdfStamper stamp = new PdfStamper(reader, new FileOutputStream(source02));//加完印章后的pdf
//			PdfContentByte over = stamp.getOverContent(1);//设置在第几页打印印章
//			Image img = Image.getInstance(TZQRH_YZ_IMG);//选择图片
//			img.setAlignment(1);
//			img.scaleAbsolute(130,130);//控制图片大小
//			img.setAbsolutePosition(400,170);//控制图片位置
//			over.addImage(img);
//			stamp.close();
//			logger.info("添加印章完成");
//		}catch(Exception e){
//			logger.info("添加电子印章错误 e={}", e);
//		}
//	}
//
//
//	private String getCode(){
//		String code = "";
//		Random random = new Random();
//		for (int i = 0; i < 12; i++) {
//			code += random.nextInt(10);
//		}
//		return code;
//	}
}
